package com.wswy.wzcx.widget

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.StateListDrawable
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.ToastUtils
import com.facebook.common.util.UriUtil
import com.facebook.drawee.view.SimpleDraweeView
import com.google.android.flexbox.FlexboxLayout
import com.stfalcon.frescoimageviewer.ImageViewer
import com.tbruyelle.rxpermissions2.RxPermissions
import com.wswy.wzcx.R
import com.wswy.wzcx.module.base.gone
import com.wswy.wzcx.module.base.visible
import com.wswy.wzcx.module.handler.TakePhotoHandler
import com.wswy.wzcx.ui.dialog.ChoosePhotoBottomDialog
import com.wswy.wzcx.utils.ImageUtils
import com.wswy.wzcx.utils.loader.FrescoEngine
import com.wswy.wzcx.widget.drawable.AddDrawable
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import java.io.File

class ImagesChooserLayout : FlexboxLayout {

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attribute: AttributeSet?) : this(context, attribute, 0)

    constructor(context: Context, attribute: AttributeSet?, defStyle: Int) : super(context, attribute, defStyle) {


        addView(SimpleDraweeView(context).apply {
            imageAdd = this
            id = R.id.img_add


            StateListDrawable().apply {
                addState(intArrayOf(android.R.attr.state_pressed), AddDrawable(context, Color.parseColor("#f0f0f0")))
                addState(intArrayOf(0),AddDrawable(context,ContextCompat.getColor(context,R.color.dark_bg_color)))

            }.run {
                hierarchy?.setPlaceholderImage(this)
            }


            setBackgroundColor(ContextCompat.getColor(context, R.color.dark_bg_color))

        },ViewGroup.MarginLayoutParams(SizeUtils.dp2px(64f),SizeUtils.dp2px(64f)).apply {

            leftMargin = SizeUtils.dp2px(4f)
            topMargin = SizeUtils.dp2px(4f)
        })

        imageAdd.setOnClickListener {
            showChooseDialog()
        }

    }


    private lateinit var imageAdd:ImageView

    private var currFiles : MutableList<File> = arrayListOf()
    private val takePhotoHandler = TakePhotoHandler()


    private val REQUEST_CODE_CHOOSE = 7702

    //private var attacthedActivity:FragmentActivity?=null
    var attachedFragment:Fragment?=null
    var maxImages = 9


    fun getFiles(): List<File> {
        return currFiles
    }

    private fun showChooseDialog(){


        ChoosePhotoBottomDialog(context).apply {

            setOnItemClickListener {
                when(it){
                    0 -> {

                        takePhotoHandler.startCamera(frag = attachedFragment){

                            currFiles.add(it)

                            showImg(currFiles)
                            updateAdd()

                            null
                        }

                    }
                    1 -> {

                        RxPermissions(attachedFragment!!)
                                .request(Manifest.permission.READ_EXTERNAL_STORAGE)
                                .subscribe { g ->

                                    if (g) {
                                        startChoose()
                                    } else {
                                        ToastUtils.showText("没有权限")
                                    }
                                }

                    }
                }
            }


        }.show()
    }

    private fun startChoose(){

        val remain = maxImages - currFiles.size
        if (remain <= 0){
            return
        }

        Matisse.from(attachedFragment).choose(MimeType.ofImage())
                .countable(true)
                .capture(false)
                .maxSelectable(remain)
                .imageEngine(FrescoEngine())
                .forResult(REQUEST_CODE_CHOOSE)

    }

    private fun showImg(imgs:List<File?>){

        for (i in 0 until childCount){

            getChildAt(0)?.let {
                if (it.id != R.id.img_add){
                    removeViewInLayout(it)
                }
            }
        }

        var len = imgs.size

        imgs.reversed().forEach {
            LayoutInflater.from(context).inflate(R.layout.feedback_add_photo,this,false)?.run {

                val position = (len--) -1

                ImageUtils.showImage(findViewById<SimpleDraweeView>(R.id.img_user_pic),it)

                findViewById<View>(R.id.img_delete)?.setOnClickListener(::clickDelete)

                setTag(R.id.item_position,position)
                setTag(R.id.item_data,imgs)
                setOnClickListener(::clickPhoto)

                addView(this,0)
            }
        }


    }

    private fun updateAdd(){
        if (currFiles.size  >= maxImages){
            imageAdd.gone()
        }else{
            imageAdd.visible()
        }
    }

    private fun clickPhoto(view: View){
        val pos = (view.getTag(R.id.item_position) as? Int)?:0

        (view.getTag(R.id.item_data) as? List<File>)?.map { UriUtil.getUriForFile(it) }?.run {
            ImageViewer.Builder(context,this)
                    .setStartPosition(pos)
                    .show()
        }

    }

    private fun clickDelete(view: View){

        (view.parent as? View)?.run {
            val idx = indexOfChild(this)

            if (idx != -1){
                removeViewAt(idx)
                currFiles.removeAt(idx)

                updateAdd()
            }

        }

    }



    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK){

            when(requestCode){
                REQUEST_CODE_CHOOSE -> { //选择图片

                    Matisse.obtainPathResult(data)?.asSequence()?.map {
                        File(it)
                    }?.filter {
                        it.exists()
                    }?.toMutableList()?.run {

                        currFiles.addAll(this)
                    }

                    currFiles.run {
                        showImg(this)
                        updateAdd()
                    }


                }


                else -> {
                    takePhotoHandler.handleActivityResult(requestCode, resultCode, data)
                }

            }


        }
    }




}